package com.lxr0860.lxr0860production_test.itemactivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


import com.lxr0860.lxr0860production_test.R;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.FileUtils;
import com.lxr0860.lxr0860production_test.view.HorizontalProgressBar;

import java.lang.reflect.Method;


public class TFActivity extends Activity implements View.OnClickListener {
    private TextView tvTip;
    private ImageView ivTF;
    private Button btnTfTest;
    private TextView mTvRightCount, mTvWrongCount;
    //自定义进度条
    private HorizontalProgressBar mProgressBar;
    private static final String DIR_PATH = "/lxr";
    private static final String FILE_PATH = "/test.txt";
    private boolean stopLoop = false;//停止测试TF卡
    private boolean isTesting;
    private String tfCardPath;
    private int repeatCount = 10;
    private int testType;

    private static final int TF_TEST_ONE_TIME = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case TF_TEST_ONE_TIME:
                    mProgressBar.setProgress(msg.arg1 + msg.arg2);
                    mTvRightCount.setText("成功次数： " + msg.arg1 + "次");
                    mTvWrongCount.setText("失败次数： " + msg.arg2 + "次");
                    if(msg.arg1+msg.arg2==repeatCount){
                        isTesting=false;
                        btnTfTest.setEnabled(true);
                    }
                    if(msg.arg1==repeatCount){
                        Contants.showDailog(TFActivity.this,"测试成功，是否保存",this, Gravity.TOP);
                    }
                    break;
                case Contants.DIALOG_POSITIVE:
                    Intent mIntent=new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putBoolean("result",true);
                    mIntent.putExtras(bundle);
                    TFActivity.this.setResult(Contants.TEST_ITEM_TF,mIntent);
                    finish();
                    break;
                case Contants.DIALOG_NEGATIVE:
                    break;
            }
        }
    };

    private void init() {
        btnTfTest = (Button) findViewById(R.id.btn_tf_start);
        btnTfTest.setEnabled(false);
        mTvRightCount = (TextView) findViewById(R.id.tv_right_count);
        mTvWrongCount = (TextView) findViewById(R.id.tv_wrong_count);
        ivTF = (ImageView) findViewById(R.id.ivTF);
        tvTip = (TextView) findViewById(R.id.tvTip);
        btnTfTest.setOnClickListener(this);
        mProgressBar = findViewById(R.id.pb_tf_progress);
        mProgressBar.setMax(repeatCount);
        //获取上个Activity传过来的值
        testType = getIntent().getIntExtra("testType", Contants.TEST_ZUZHUANG);
        if (getTFCardInfo() == 0) {
            tvTip.append(FileUtils.getGB(tfCardPath));
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_tf_card);
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopLoop=true;
    }

    @Override
    public void onClick(View v) {
        if (v.getId()== R.id.btn_tf_start) {
            testTf();
        }
    }

    private void testTf() {
        if(isTesting){
            return;
        }
        isTesting=true;
        btnTfTest.setEnabled(false);
        mProgressBar.setProgress(0);
        new Thread(new Runnable() {
            @Override
            public void run() {
                int rightCount = 0;
                int wrongCount = 0;
                for (int i = 0; i < repeatCount; i++) {
                    if (stopLoop) {
                        return;
                    }
                    if (testTfCard()) {
                        rightCount++;
                    } else {
                        wrongCount++;
                    }
                    Message msg = Message.obtain();
                    msg.arg1 = rightCount;
                    msg.arg2 = wrongCount;
                    msg.what = TF_TEST_ONE_TIME;
                    handler.sendMessage(msg);

                }
            }
        }).start();
    }

    private boolean testTfCard() {
        return FileUtils.creatFile(tfCardPath+ DIR_PATH, FILE_PATH)
                &&FileUtils.writeDataToTfCard(tfCardPath + DIR_PATH + FILE_PATH)
                &&FileUtils.copyFile(tfCardPath + DIR_PATH + FILE_PATH,
                tfCardPath + DIR_PATH + "/newfile.log")
                &&FileUtils.deleteFile(tfCardPath + DIR_PATH);
    }

    private int getTFCardInfo() {
        StorageManager storageManager = (StorageManager) getApplicationContext()
                .getSystemService(STORAGE_SERVICE);
        StorageVolume[] storageVolumes;
        try {
            Method getVolumeList = StorageManager.class.getDeclaredMethod("getVolumeList");
            storageVolumes = (StorageVolume[]) getVolumeList.invoke(storageManager);
            Method getVolumeState = StorageManager.class
                    .getDeclaredMethod("getVolumeState", String.class);
            for (StorageVolume storageVolume : storageVolumes) {
                String desc = storageVolume.getDescription(this);
                if (desc.contains("SD")) {
                    Method getPath = StorageVolume.class.getMethod("getPath");
                    tfCardPath = (String) getPath.invoke(storageVolume);
                    String state = (String) getVolumeState
                            .invoke(storageManager, tfCardPath);
                    if (Environment.MEDIA_MOUNTED.equals(state)) {
                        tvTip.setText("检测到TF卡，TF卡挂载成功!");
                        ivTF.setBackgroundResource(R.drawable.tf_mounted);
                        btnTfTest.setEnabled(true);
                        return 0;
                    } else {
                        tvTip.setText("检测到TF卡，TF卡挂载失败!");
                        ivTF.setBackgroundResource(R.drawable.tf_unmounted);
                        btnTfTest.setEnabled(false);
                        return -1;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        tvTip.setText("未检测到TF卡");
        ivTF.setBackgroundResource(R.drawable.tf_unmounted);
        return -2;
    }
}